<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>钩子管理</title>
    <link rel="stylesheet" href="/static/css/bulma.min.css">
    <script src="/static/js/jquery/jquery.min.js"></script>
    <style>
        .container {
            max-width: 1200px;
            margin: 20px auto;
        }
        .hook-card {
            margin-bottom: 20px;
        }
        .hook-name {
            font-family: 'Courier New', monospace;
            background: #f5f5f5;
            padding: 2px 6px;
            border-radius: 3px;
        }
        .handler-item {
            background: #fafafa;
            border-left: 3px solid #3273dc;
            padding: 10px;
            margin: 5px 0;
        }
        .plugin-badge {
            font-size: 0.8em;
        }
        .tabs-container {
            margin-bottom: 20px;
        }

        @keyframes slideInRight {
            from {
                transform: translateX(100%);
                opacity: 0;
            }
            to {
                transform: translateX(0);
                opacity: 1;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="box">
            <h1 class="title">钩子管理</h1>
            <p class="subtitle">管理系统中所有插件注册的钩子</p>
        </div>

        <div class="tabs-container">
            <div class="tabs is-boxed">
                <ul>
                    <li class="is-active" data-tab="plugin-hooks">
                        <a>
                            <span>插件钩子</span>
                        </a>
                    </li>
                    <li data-tab="system-hooks">
                        <a>
                            <span>系统钩子</span>
                        </a>
                    </li>
                </ul>
            </div>
        </div>

        <!-- 插件钩子标签页 -->
        <div id="plugin-hooks" class="tab-content">
            <div class="box">
                <h2 class="subtitle">插件钩子概览</h2>
                <div id="plugin-hooks-content">
                    <div class="has-text-centered" style="padding: 50px;">
                        <span class="icon is-large">
                            <i class="fas fa-spinner fa-pulse"></i>
                        </span>
                        <p>加载中...</p>
                    </div>
                </div>
            </div>
        </div>

        <!-- 系统钩子标签页 -->
        <div id="system-hooks" class="tab-content" style="display: none;">
            <div class="box">
                <h2 class="subtitle">系统已注册钩子</h2>
                <div id="system-hooks-content">
                    <div class="has-text-centered" style="padding: 50px;">
                        <span class="icon is-large">
                            <i class="fas fa-spinner fa-pulse"></i>
                        </span>
                        <p>加载中...</p>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        class HookManager {
            constructor() {
                this.baseUrl = '/adminapi/plugin/manager';
                this.currentTab = 'plugin-hooks';
                this.init();
            }

            init() {
                this.bindEvents();
                this.loadPluginHooks();
            }

            bindEvents() {
                // 标签页切换
                $('.tabs li').on('click', (e) => {
                    const $tab = $(e.currentTarget);
                    const tabName = $tab.data('tab');
                    
                    $('.tabs li').removeClass('is-active');
                    $tab.addClass('is-active');
                    
                    $('.tab-content').hide();
                    $(`#${tabName}`).show();
                    
                    this.currentTab = tabName;
                    
                    if (tabName === 'system-hooks' && !this.systemHooksLoaded) {
                        this.loadSystemHooks();
                    }
                });
            }

            async request(url, options = {}) {
                const token = localStorage.getItem('admin_token');
                const defaultOptions = {
                    headers: {
                        'Authorization': `Bearer ${token}`,
                        'Content-Type': 'application/json'
                    }
                };

                const response = await fetch(url, { ...defaultOptions, ...options });
                const data = await response.json();

                if (data.code !== 1) {
                    throw new Error(data.msg || '请求失败');
                }

                return data.data;
            }

            async loadPluginHooks() {
                try {
                    const data = await this.request(`${this.baseUrl}/getAllHooks`);
                    this.renderPluginHooks(data);
                } catch (error) {
                    this.showError('plugin-hooks-content', '加载插件钩子失败: ' + error.message);
                }
            }

            async loadSystemHooks() {
                try {
                    const data = await this.request(`${this.baseUrl}/getSystemHooks`);
                    this.renderSystemHooks(data);
                    this.systemHooksLoaded = true;
                } catch (error) {
                    this.showError('system-hooks-content', '加载系统钩子失败: ' + error.message);
                }
            }

            renderPluginHooks(data) {
                const container = document.getElementById('plugin-hooks-content');
                
                if (Object.keys(data).length === 0) {
                    container.innerHTML = `
                        <div class="has-text-centered" style="padding: 50px; color: #999;">
                            <p>暂无插件注册钩子</p>
                        </div>
                    `;
                    return;
                }

                let html = '';
                for (const [pluginName, pluginData] of Object.entries(data)) {
                    const pluginInfo = pluginData.plugin_info;
                    const hooks = pluginData.hooks;
                    
                    html += `
                        <div class="card hook-card">
                            <div class="card-header">
                                <div class="card-header-title">
                                    <span class="tag is-primary plugin-badge">${pluginName}</span>
                                    <span style="margin-left: 10px;">${pluginInfo.title || pluginName}</span>
                                    <span class="tag is-light" style="margin-left: auto;">${hooks.length} 个钩子</span>
                                </div>
                            </div>
                            <div class="card-content">
                                ${hooks.map(hook => `
                                    <div class="hook-item" style="margin-bottom: 15px;">
                                        <div class="level">
                                            <div class="level-left">
                                                <div class="level-item">
                                                    <strong class="hook-name">${hook.hook_name}</strong>
                                                    <span class="tag is-${hook.enabled ? 'success' : 'danger'} is-small" style="margin-left: 10px;">
                                                        ${hook.enabled ? '已启用' : '已禁用'}
                                                    </span>
                                                </div>
                                            </div>
                                            <div class="level-right">
                                                <div class="level-item">
                                                    <span class="tag is-info is-small">${hook.handlers.length} 个处理器</span>
                                                </div>
                                                <div class="level-item">
                                                    <div class="buttons are-small">
                                                        ${hook.enabled ?
                                                            `<button class="button is-warning is-small" onclick="window.hookManager.toggleHook('${pluginName}', '${hook.hook_name}', false)">禁用</button>` :
                                                            `<button class="button is-success is-small" onclick="window.hookManager.toggleHook('${pluginName}', '${hook.hook_name}', true)">启用</button>`
                                                        }
                                                        <button class="button is-danger is-small" onclick="window.hookManager.deleteHook('${pluginName}', '${hook.hook_name}')">删除</button>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        ${hook.handlers.map(handler => `
                                            <div class="handler-item">
                                                <div class="columns is-mobile">
                                                    <div class="column">
                                                        <strong>类:</strong> <code>${handler.class}</code>
                                                    </div>
                                                    <div class="column">
                                                        <strong>方法:</strong> <code>${handler.method}</code>
                                                    </div>
                                                    <div class="column is-narrow">
                                                        <div class="field has-addons">
                                                            <div class="control">
                                                                <input class="input is-small" type="number" value="${handler.priority}"
                                                                       id="priority-${pluginName}-${hook.hook_name}-${handler.index}"
                                                                       style="width: 80px;">
                                                            </div>
                                                            <div class="control">
                                                                <button class="button is-small is-primary"
                                                                        onclick="window.hookManager.updatePriority('${pluginName}', '${hook.hook_name}', ${handler.index})">
                                                                    更新
                                                                </button>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        `).join('')}
                                    </div>
                                `).join('')}
                            </div>
                        </div>
                    `;
                }

                container.innerHTML = html;
            }

            renderSystemHooks(data) {
                const container = document.getElementById('system-hooks-content');
                
                if (data.length === 0) {
                    container.innerHTML = `
                        <div class="has-text-centered" style="padding: 50px; color: #999;">
                            <p>暂无系统钩子</p>
                        </div>
                    `;
                    return;
                }

                let html = '';
                data.forEach(hook => {
                    html += `
                        <div class="card hook-card">
                            <div class="card-header">
                                <div class="card-header-title">
                                    <strong class="hook-name">${hook.hook_name}</strong>
                                    <span class="tag is-light" style="margin-left: auto;">${hook.handler_count} 个处理器</span>
                                </div>
                            </div>
                            <div class="card-content">
                                ${hook.handlers.map(handler => `
                                    <div class="handler-item">
                                        <div class="columns is-mobile">
                                            <div class="column">
                                                <strong>类:</strong> <code>${handler.class}</code>
                                            </div>
                                            <div class="column">
                                                <strong>方法:</strong> <code>${handler.method}</code>
                                            </div>
                                            <div class="column is-narrow">
                                                <span class="tag is-${handler.plugin === 'system' ? 'warning' : 'primary'} is-small">
                                                    ${handler.plugin}
                                                </span>
                                            </div>
                                        </div>
                                    </div>
                                `).join('')}
                            </div>
                        </div>
                    `;
                });

                container.innerHTML = html;
            }

            showError(containerId, message) {
                const container = document.getElementById(containerId);
                container.innerHTML = `
                    <div class="notification is-danger">
                        <p>${message}</p>
                    </div>
                `;
            }

            async toggleHook(pluginName, hookName, enable) {
                try {
                    const action = enable ? 'enableHook' : 'disableHook';
                    const actionText = enable ? '启用' : '禁用';

                    if (!confirm(`确定要${actionText}钩子 "${hookName}" 吗？\n\n注意：此操作将重新加载webman服务。`)) {
                        return;
                    }

                    // 显示加载提示
                    this.showNotification(`正在${actionText}钩子，webman服务重载中...`, 'info');

                    await this.request(`${this.baseUrl}/${action}`, {
                        method: 'POST',
                        body: JSON.stringify({
                            plugin_name: pluginName,
                            hook_name: hookName
                        })
                    });

                    // 延迟重新加载，给webman重载时间
                    setTimeout(() => {
                        this.loadPluginHooks();
                        this.showNotification(`钩子已${actionText}，webman服务已重载`, 'success');
                    }, 2000);

                } catch (error) {
                    this.showNotification(`${enable ? '启用' : '禁用'}失败: ` + error.message, 'danger');
                }
            }

            async deleteHook(pluginName, hookName) {
                try {
                    if (!confirm(`确定要删除钩子 "${hookName}" 吗？\n\n此操作不可恢复，且将重新加载webman服务！`)) {
                        return;
                    }

                    // 显示加载提示
                    this.showNotification('正在删除钩子，webman服务重载中...', 'info');

                    await this.request(`${this.baseUrl}/deleteHook`, {
                        method: 'POST',
                        body: JSON.stringify({
                            plugin_name: pluginName,
                            hook_name: hookName
                        })
                    });

                    // 延迟重新加载，给webman重载时间
                    setTimeout(() => {
                        this.loadPluginHooks();
                        this.showNotification('钩子已删除，webman服务已重载', 'success');
                    }, 2000);

                } catch (error) {
                    this.showNotification('删除失败: ' + error.message, 'danger');
                }
            }

            async updatePriority(pluginName, hookName, handlerIndex) {
                try {
                    const inputId = `priority-${pluginName}-${hookName}-${handlerIndex}`;
                    const priorityInput = document.getElementById(inputId);
                    const priority = parseInt(priorityInput.value);

                    if (isNaN(priority)) {
                        this.showNotification('请输入有效的优先级数字', 'warning');
                        return;
                    }

                    if (!confirm(`确定要更新钩子优先级吗？\n\n此操作将重新加载webman服务。`)) {
                        return;
                    }

                    // 显示加载提示
                    this.showNotification('正在更新优先级，webman服务重载中...', 'info');

                    await this.request(`${this.baseUrl}/updateHookPriority`, {
                        method: 'POST',
                        body: JSON.stringify({
                            plugin_name: pluginName,
                            hook_name: hookName,
                            handler_index: handlerIndex,
                            priority: priority
                        })
                    });

                    // 延迟显示成功消息，给webman重载时间
                    setTimeout(() => {
                        this.showNotification('优先级已更新，webman服务已重载', 'success');
                    }, 2000);

                } catch (error) {
                    this.showNotification('更新失败: ' + error.message, 'danger');
                }
            }

            showNotification(message, type = 'info') {
                // 创建通知元素
                const notification = document.createElement('div');
                notification.className = `notification is-${type}`;
                notification.style.cssText = `
                    position: fixed;
                    top: 20px;
                    right: 20px;
                    z-index: 9999;
                    min-width: 300px;
                    animation: slideInRight 0.3s ease;
                `;
                notification.innerHTML = `
                    <button class="delete" onclick="this.parentElement.remove()"></button>
                    ${message}
                `;

                document.body.appendChild(notification);

                // 3秒后自动移除
                setTimeout(() => {
                    if (notification.parentElement) {
                        notification.remove();
                    }
                }, 3000);
            }
        }

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', () => {
            window.hookManager = new HookManager();
        });
    </script>
</body>
</html>
